package Controller;

import Model.CSGrade;
import Model.CSGradeBean;
import Model.Result;
import Model.ResultBean;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/Dafen3")
public class Dafen3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        Context context = null;
        HttpSession session = request.getSession();
        try {
            context = new InitialContext();
            Context contextNeeded = (Context) context.lookup("java:comp/env");
            DataSource ds = (DataSource) contextNeeded.lookup("wq");// 获得连接池。
            Connection conn = null;
            ResultSet rs;
            String sql;
            PreparedStatement pstmt;
            conn = ds.getConnection();//获得数据源

            CSGradeBean sb = (CSGradeBean) session.getAttribute("csgradeBean");

            ArrayList<CSGrade> temp;
            temp = sb.getCsGradeArrayList();

            for(int i=0;i<temp.size();i++){
                temp.get(i).setGrade(request.getParameter("grade"+i));
                System.out.println(temp.get(i).getGrade());
            }
            sb.setCsGradeArrayList(temp);
            session.setAttribute("csgradeBean",sb);

            for (int i=0;i<temp.size();i++){
                sql = "update score set grade=? where id=? and sno=?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1,temp.get(i).getGrade());
                pstmt.setString(2,temp.get(i).getId());
                pstmt.setString(3,temp.get(i).getSno());
                pstmt.executeUpdate();
            }
            conn.close();
            response.getWriter().write("<script language='javascript'>alert('提交成功！');" +
                    "window.location.href='/caipan/dafen.jsp';</script>");
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("加载不成功");
        }
    }
}
